package com.college.dao;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Formatter;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.college.domain.Batch;
import com.college.domain.Department;
import com.college.domain.Roles;
import com.college.domain.Student;
import com.college.domain.Users;
import com.college.interfaces.IConfigurationDAO;
import com.college.interfaces.IFacultyDAO;
import com.college.interfaces.IRolesDAO;
import com.college.interfaces.IStudentDAO;
import com.college.interfaces.IUserDAO;
import com.college.util.Encryption;

@Repository
@Transactional
public class StudentDAO implements IStudentDAO {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Autowired
	private IConfigurationDAO configDAO;

	@Autowired
	private IUserDAO userDAO;
	
	@Autowired
	private IRolesDAO rolesDAO;
	
	@Override
	public int saveStudentInfo(List<Student> stu) {
		for(Student stud:stu){			
			
			if(!stud.getFirstName().equals("") && !stud.getLastName().equals("")){
			List<Department> deptList = configDAO.getDeptByName(stud.getDeptName());
			for(Department dept:deptList){
				stud.setDeptId(dept.getDeptId());
			}
			List<Batch> batchList = configDAO.getBatchByBatchName(stud.getBatchName());
			for(Batch batch:batchList){
				stud.setBatchId(batch.getBatchId());
			}
		
			Users user = new Users();
			user.setEnabled("Y");
			Format formatter = new SimpleDateFormat("dd/MM/yyyy");
			user.setPassword(Encryption.encrypt(formatter.format(stud.getDob())));
			String pass = user.getPassword();
			String newPass = "0"+pass;
			user.setPassword(newPass);
			user.setUserName(stud.getRegNo());
			int saveStatus = userDAO.saveUser(user);
			
			Roles role = new Roles();
			role.setAuthority(stud.getRoleName());
			role.setRoleDescription("Student");
			role.setRoleName("ROLE_STUDENT");
			List<Users> userObj =  userDAO.getUserByUsername(stud.getRegNo());
			for(Users user1: userObj){
				role.setUserId(user1.getUserId());
				}
			rolesDAO.saveRole(role);
			List<Roles> roleList = rolesDAO.getRoleByUserId(Integer.valueOf(role.getUserId()));
				for(Roles role1:roleList){
					stud.setRoleId(role1.getRoleId());
				}
				saveStudent(stud);
			}
			}
		
		
		return 0;
	}
	
	@Override
	public int saveStudent(Student student) {
		return (Integer) sessionFactory.getCurrentSession().save(student);
	}

	public List<Student> getStudentNameById(String name) {
		return   sessionFactory.getCurrentSession().createQuery("from Student where regNo=:name").setString("name", name).list();		
	}
	

}
